package day1219;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class Client2 {
    public static void main(String[] args) throws IOException {
        Client2 c=new Client2();//创建客户端对象
        c.start();
    }


    //内部类创建线程
    class  ReceiveFromServer  extends  Thread{
        Socket  so;
        ReceiveFromServer(Socket s){///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            so=s;
        }
        public  void run(){
            try {
                BufferedReader br=new BufferedReader(
                        new InputStreamReader (s.getInputStream(),"UTF-8"));
                String msg=null;
                while(   (msg=br.readLine())!=null   ){
                    System.out.println(msg);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void start() throws IOException {
        //创建一个线程对象(接收服务器返回的数据)
        ReceiveFromServer  rfs=new ReceiveFromServer(s);
        rfs.start();

        //2.用Socket的输出流给服务器发送数据
        OutputStream out=s.getOutputStream();//字节输出流
        OutputStreamWriter  writer=new OutputStreamWriter(out,"UTF-8");//字符输出流
        PrintWriter  pw=new PrintWriter(writer);


        //3.用输出流给服务器发送数据
        Scanner   sc=new Scanner(System.in);
        while(true){
            System.out.println("请输入您想要发送的消息：");
            String msg=sc.nextLine();//3.1.用户用Scanner输入文字
            pw.println(msg);//3.2.用PrintWriter  pw将用户输入的文字发送到服务器
            pw.flush();
        }

    }

    Socket s=null;
    Client2() throws IOException {
        //1.构造方法，用new Socket(信息)连接服务器
        s=new Socket("10.172.201.245",8089);
    }

}
